package com.koron.common.core.business.system;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.koron.bean.system.org.OrgBean;
import com.koron.bean.system.org.OrgVo;
import com.koron.bean.system.role.AppMenuJurisdictionBean;
import com.koron.bean.system.staff.Constant;
import com.koron.bean.system.staff.vo.EamUser;
import com.koron.bean.util.JWTUtils;
import com.koron.bean.util.RedisUtils;
import com.koron.common.core.business.configsettings.utils.ConfigInfoTool;
import com.koron.common.core.util.OrgCacheUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName SystemCacheUtil
 * @description
 * @Author zhouj
 * @Date 2021/10/25 10:35
 */
@RefreshScope
@Component
public class SystemCacheUtil {

    private static Integer expired;

    @Value("${jwt.expired:1}")
    public void setExpired(Integer expired) {
        SystemCacheUtil.expired = expired;
    }

    //缓存用户信息
    public static void cacheUserInfo(EamUser eamUser, String token) {

        //添加token到用户信息token列表
        if (StringUtils.isNotEmpty(token)) {
            List<String> tokenList = eamUser.getTokenList();
            if (CollectionUtils.isNotEmpty(tokenList)) {
                if (!tokenList.contains(token)) {
                    tokenList.add(token);
                }
            } else {
                List<String> list = new ArrayList<>();
                list.add(token);
                eamUser.setTokenList(list);
            }
        }

        cacheUserInfo(eamUser);

    }

    //缓存代理领导的用户信息
    public static void cacheAgentLeaderInfo(EamUser eamUser, String agent) {

        if (Objects.isNull(eamUser) || Objects.isNull(eamUser.getUserOwnJurisdictionBean())) {
            return;
        }

        //因菜单数据太多,且暂时只有前端使用到,选择不存入redis
        List<AppMenuJurisdictionBean> appMenuJurisdictionBeanList = eamUser.getUserOwnJurisdictionBean().getAppMenuJurisdictionBeanList();
        eamUser.getUserOwnJurisdictionBean().setAppMenuJurisdictionBeanList(new ArrayList<>());
        String jsonString = JSON.toJSONString(eamUser);
        if (expired == 1) {
            Map<String, String> map = ConfigInfoTool.getConfigByCode("common", "jwt");
            expired = Integer.valueOf(map.get("expired"));
        }
        RedisUtils.hset(Constant.EAM_SERVICE_AUTH_AGENT + ":" + agent, eamUser.getAccount(), jsonString, expired);
        //重新设置回去
        eamUser.getUserOwnJurisdictionBean().setAppMenuJurisdictionBeanList(appMenuJurisdictionBeanList);
    }

    //缓存用户信息
    public static void cacheUserInfo(EamUser eamUser) {

        if (Objects.isNull(eamUser) || Objects.isNull(eamUser.getUserOwnJurisdictionBean())) {
            return;
        }

        //清理一下过期token
        List<String> tokenList = eamUser.getTokenList();
        if (!CollectionUtils.isEmpty(tokenList)) {
            List<String> newTokenList = new ArrayList<>();
            for (String token : tokenList) {
                DecodedJWT verify = JWTUtils.verify(token);
                if (verify != null) {
                    newTokenList.add(token);
                }
            }
            eamUser.setTokenList(newTokenList);
        }

        //给组织加上部门
        List<OrgVo> orgVoList = eamUser.getOrgVoList();
        if (CollectionUtils.isNotEmpty(orgVoList)) {
            for (OrgVo orgVo : orgVoList) {
                OrgBean deptBean = queryDeptByOrgId(orgVo.getId());
                if (!Objects.isNull(deptBean)) {
                    orgVo.setDeptId(deptBean.getId());
                    orgVo.setDeptName(deptBean.getName());
                }
            }
        }

        //因菜单数据太多,且暂时只有前端使用到,选择不存入redis
        List<AppMenuJurisdictionBean> appMenuJurisdictionBeanList = eamUser.getUserOwnJurisdictionBean().getAppMenuJurisdictionBeanList();
        eamUser.getUserOwnJurisdictionBean().setAppMenuJurisdictionBeanList(new ArrayList<>());
        String jsonString = JSON.toJSONString(eamUser);
        if (expired == 1) {
            Map<String, String> map = ConfigInfoTool.getConfigByCode("common", "jwt");
            expired = Integer.valueOf(map.get("expired"));
        }

        RedisUtils.hset(Constant.EAM_SERVICE_AUTH, eamUser.getAccount(), jsonString, expired);
        //重新设置回去
        eamUser.getUserOwnJurisdictionBean().setAppMenuJurisdictionBeanList(appMenuJurisdictionBeanList);
    }

    //获取新的token
    public static String getNewToken(String account, String userName) {

        Map<String, String> map = new HashMap<>();
        map.put(Constant.ACCOUNT, account);
        map.put(Constant.USERNAME, userName);
        String token = JWTUtils.getToken(map, expired);

        return token;

    }

    //获取当前用户redis用户信息
    public static EamUser getRedisUser(String account) {
        String userStr = (String) RedisUtils.hget(Constant.EAM_SERVICE_AUTH, account);

        if (StringUtils.isNotEmpty(userStr)) {
            return JSON.parseObject(userStr, EamUser.class);
        }
        return null;
    }

    //获取代理领导的redis用户信息
    public static EamUser getAgentLeaderRedisUser(String leader, String agent) {
        String userStr = (String) RedisUtils.hget(Constant.EAM_SERVICE_AUTH_AGENT + ":" + agent, leader);

        if (StringUtils.isNotEmpty(userStr)) {
            return JSON.parseObject(userStr, EamUser.class);
        }
        return null;
    }

    //验证token
    public static String verifyToken(String token) {

        if (StringUtils.isNotEmpty(token)) {
            DecodedJWT verify = JWTUtils.verify(token);
            if (verify != null) {
                String t_account = verify.getClaim(Constant.ACCOUNT).asString();
                return t_account;
            }
        }
        return null;
    }

    //验证账号是否过期
    public static void vertifyAccountExpire(EamUser eamUser) {
        if (eamUser == null) {
            return;
        }
        Date nowDate = new Date();

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        String nowDateStr = dateFormat.format(nowDate);

        Date accountExpiringTime = eamUser.getAccountExpiringTime();

        if (!Objects.isNull(accountExpiringTime)) {
            Assert.isTrue(dateFormat.format(accountExpiringTime).compareTo(nowDateStr) == 1, "该账号信息已过期,过期时间:" + dateFormat.format(accountExpiringTime));
        }


    }

    //缓存登录时用到的公钥和私钥
    public static void cacheRsa(Map<Integer, String> cond) {

        if (MapUtils.isEmpty(cond)) {
            return;
        }

        RedisUtils.hset("rsa", "publicKey", cond.get(0));
        RedisUtils.hset("rsa", "privateKey", cond.get(1));

    }

    //缓存登录时用到的公钥和私钥
    public static Map<Integer, String> getCacheRsa() {

        Map<Integer, String> cond = new HashMap<>();
        String publicKey = (String) RedisUtils.hget("rsa", "publicKey");
        String privateKey = (String) RedisUtils.hget("rsa", "privateKey");

        if (StringUtils.isAnyEmpty(publicKey, privateKey)) {
            return cond;
        }
        cond.put(0, publicKey);
        cond.put(1, privateKey);
        return cond;
    }

    public static OrgBean queryDeptByOrgId(String orgId) {

        OrgBean orgBean = OrgCacheUtils.queryDeptByOrgId(orgId);
        if (orgBean == null) {
            return null;
        }
        if ("2".equals(orgBean.getLevel())) {
            //本身为部门
            return orgBean;
        } else {
            //向上循环查询第一级部门
            String levelPath = orgBean.getLevelPath();
            String[] split = levelPath.split("/");
            for (int i = split.length - 1; i >= 0; i--) {
                OrgBean orgBean1 = OrgCacheUtils.queryDeptByOrgId(split[i]);
                if (orgBean1 != null && "2".equals(orgBean1.getLevel())) {
                    return orgBean1;
                }
            }
        }
        return null;
    }

    public static OrgBean queryUpByOrgId(String orgId) {

        OrgBean orgBean = OrgCacheUtils.queryDeptByOrgId(orgId);
        if (orgBean == null) {
            return null;
        }

        //向上循环查
        String levelPath = orgBean.getLevelPath();
        String[] split = levelPath.split("/");
        for (int i = split.length - 1; i >= 0; i--) {
            OrgBean orgBean1 = OrgCacheUtils.queryDeptByOrgId(split[i]);
            if (orgBean1 != null) {
                return orgBean1;
            }
        }
        return null;
    }

}
